// 文件：controllers/postsController.js
const postService = require("../services/postService");
const inputValidator = require("../utils/inputValidator");
const { errorResponse, successResponse } = require("../utils/response");

exports.getAllPosts = async (ctx) => {
  try {
    const posts = await postService.getAllPosts();
    ctx.body = successResponse(posts, "获取所有帖子成功");
  } catch (error) {
    ctx.body = errorResponse(error);
  }
};

exports.getPostById = async (ctx) => {
  try {
    inputValidator.validateId(ctx.params.id);
    const post = await postService.getPostById(ctx.params.id);
    ctx.body = successResponse(post, "获取帖子成功");
  } catch (error) {
    ctx.body = errorResponse(error);
  }
};

exports.createPost = async (ctx) => {
  try {
    inputValidator.validatePost(ctx.request.body);
    const newPost = await postService.createPost(ctx.request.body);
    ctx.body = successResponse(newPost, "创建帖子成功");
  } catch (error) {
    ctx.body = errorResponse(error);
  }
};

exports.updatePost = async (ctx) => {
  try {
    inputValidator.validateId(ctx.params.id);
    inputValidator.validatePost(ctx.request.body);
    const updatedPost = await postService.updatePost(
      ctx.params.id,
      ctx.request.body,
    );
    ctx.body = successResponse(updatedPost, "更新帖子成功");
  } catch (error) {
    ctx.body = errorResponse(error);
  }
};

exports.deletePost = async (ctx) => {
  try {
    inputValidator.validateId(ctx.params.id);
    await postService.deletePost(ctx.params.id);
    ctx.body = successResponse(true, "删除帖子成功");
  } catch (error) {
    ctx.body = errorResponse(error);
  }
};
